package com.javacoo.swing.jxbrowser.content;

import java.awt.BorderLayout;

import javax.swing.JFrame;
import javax.swing.WindowConstants;

import com.javacoo.swing.jxbrowser.BaseBrowser;
import com.teamdev.jxbrowser.chromium.Browser;
import com.teamdev.jxbrowser.chromium.Certificate;
import com.teamdev.jxbrowser.chromium.CertificateErrorParams;
import com.teamdev.jxbrowser.chromium.DefaultLoadHandler;
import com.teamdev.jxbrowser.chromium.swing.BrowserView;

/**
 * 处理SSL证书错误
 * <li></li>
 * 默认情况下，JxBrowser允许使用无效的SSL证书加载HTTPS网站。如果您需要更改此默认行为并且不允许无效的SSL证书，则可以在您决定是否应忽略无效SSL证书的情况下注册自己的LoadHandler实现
 * 例如：
 *
 * browser.setLoadHandler(new DefaultLoadHandler() {
 *     @Override
 *     public boolean onCertificateError(CertificateErrorParams params) {
 *         // Return false to ignore certificate error.
 *         return false;
 *     }
 * });
 *
 * 该 CertificateErrorParams 参数提供了有关SSL证书无效信息。您可以使用其详细信息来决定是否允许证书
 * @author: duanyong@jccfc.com
 * @since: 2020/9/25 10:17
 */
public class HandlingSSLCertificateErrors extends BaseBrowser {
    public static void main(String[] args) {
        Browser browser = new Browser();
        BrowserView browserView = new BrowserView(browser);

        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.add(browserView, BorderLayout.CENTER);
        frame.setSize(700, 500);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);

        browser.setLoadHandler(new DefaultLoadHandler() {
            @Override
            public boolean onCertificateError(CertificateErrorParams params) {
                Certificate certificate = params.getCertificate();
                System.out.println("subjectName = " + certificate.getSubjectName());
                System.out.println("issuerName = " + certificate.getIssuerName());
                System.out.println("hasExpired = " + certificate.hasExpired());
                System.out.println("errorCode = " + params.getCertificateError());
                // Return false to ignore certificate error.
                return false;
            }
        });
        browser.loadURL("<https-url-with-invalid-ssl-certificate>");
    }
}
